<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>滚动事件</title>
    <style>
      body {
        height: 2000px;
      }

      #btnTop {
        position: fixed;
        right: 20px;
        bottom: 20px;
      }
    </style>
  </head>

  <body>
    <button id="btnTop" style="display: block">返回顶部</button>

    <script>
      /* 监听浏览器的滚动事件 */
      window.onscroll = function () {
        // scrollTop一旦达到500像素 则回顶部按钮可见 否则消失
        console.log(window.scrollY, document.documentElement.scrollTop);

        if (document.documentElement.scrollTop >= 500) {
          btnTop.style.display = "block";
        } else {
          btnTop.style.display = "none";
        }
      };

      btnTop.onclick = function () {
        // console.log("拿开你的咸猪手");
        // document.documentElement.scrollTop = 0

        /* 每40毫秒(一帧)修正一下scrollTop */
        var timerId = window.setInterval(
          // 每40毫秒回调一次 一秒25帧
          function () {
            //   每帧回一点点
            document.documentElement.scrollTop -= 200;

            //   一旦scrollTop来到0 就移除定时器
            if (document.documentElement.scrollTop === 0) {
              window.clearInterval(timerId);
              console.log("动画定时器已移除");
            }
          },
          40
        );
      };
    </script>
  </body>
</html>
